package com.bos.service.impl;

import com.bos.dao.repositories.AreaRepository;
import com.bos.domian.base.Area;
import com.bos.service.AreaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author misterWei
 * @create 2018年11月13号:17点03分
 * @mailbox mynameisweiyan@gmail.com
 */
@Service
@Transactional
public class AreaServiceImpl implements AreaService {


    @Autowired
    private AreaRepository areaRepository;

    @Override
    public void savaBatch(List<Area> areas) {
        areaRepository.save(areas);
    }

    @Override
    public Map<String, Object> pageQuery(Integer page, Integer rows,Area area) {
        Page<Area> all = null;
        if (area!=null) {
            Specification<Area> specification =  new Specification<Area>() {
                Predicate and = null;
                @Override
                public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    if (StringUtils.isNotBlank(area.getProvince())) {
                        Predicate province1 = cb.like(root.get("province").as(String.class), "%" + area.getProvince() + "%");

                        and = cb.and(province1);
                    }
                    if (StringUtils.isNotBlank(area.getCity())) {
                        Predicate province1 = cb.like(root.get("city").as(String.class), "%" + area.getCity() + "%");

                        and = cb.and(province1);
                    }
                    if (StringUtils.isNotBlank(area.getDistrict())) {
                        Predicate province1 = cb.like(root.get("district").as(String.class), "%" + area.getDistrict() + "%");

                        and = cb.and(province1);
                    }

                    return and;
                }
            };
           all = areaRepository.findAll(specification,new PageRequest(page, rows));
        }else {
           all =  areaRepository.findAll(new PageRequest(page, rows));
        }

        Map<String,Object> areaList = new HashMap<>();
        areaList.put("total",all.getTotalElements());
        areaList.put("rows",all.getContent());
        return areaList;
    }

}
